%% @author Administrator
%% @doc @todo Add description to http_app.


-module(http_app).

-behaviour(application).

-export([start/2, stop/1]).
-include("common.hrl").

start(_StartType, _StartArgs) -> 
	{ok, Name} = application:get_env(name),
	{ok, Cookie} = application:get_env(cookie),
	{ok,Dbm}=application:get_env(dbm),
	net_kernel:start([Name, longnames]),
	util:sleep(2000),
	erlang:set_cookie(node(), Cookie),
	check_start(Dbm).

check_start(Dbm) ->
	?log_trace("connect dbm..."),
	case net_adm:ping(Dbm) of
		pong -> 
			wait_for_dbm_init(),
			do_start();					
		_ -> util:sleep(2000),
			 check_start(Dbm)
	end.

wait_for_dbm_init() ->
	?log_trace("wait for dbm init..."),
	case server_tools:call_persist({global, dbm}, where, 2000) of
		{ok, _Node} -> ok;
		_ -> wait_for_dbm_init()
	end.
stop(_State) ->    
    ok.

do_start()-> 
	inets:start(),
	ssl:start(),
	application:start(crypto),
	application:start(sasl),
	application:start(ranch),
	application:start(cowlib),
	application:start(cowboy),	
    case http_sup:start_link() of      
        {ok, Pid} -> {ok, Pid};
        Other ->     {error, Other}
    end.